﻿using System;
using System.Linq;
using System.Drawing;
using System.ComponentModel;
using System.Windows.Forms;
using LinqKit;
using Syncfusion.Drawing;
using Syncfusion.Windows.Forms;
using Syncfusion.Windows.Forms.Grid;
using Syncfusion.Windows.Forms.Grid.Grouping;

using PMngr.Data;

namespace PMngr.Main
{
    public partial class AdminReport : BaseControl, IControl
    {
        private IRepository repository;

        public AdminReport()
        {
            InitializeComponent();
            // GridGroupingControl
            InitializeGridGrouping();
        }

        public AdminReport(IRepository repository)
            : this()
        {
            this.repository = repository;
                          
        }

        public override void InitializeControls()
        {
            // 单位区域，单位性质
            InitializeDropDownList();
        }

        private void InitializeDropDownList()
        {
            // 单位区域
            var options1 = repository.All<ItemBase>();
            var datasource1 = from o in options1
                              where o.Type == "UnitType" && o.IsValid == true
                              orderby o.Order
                              select new { Code = o.Code, Name = o.Name };
            var result1 = datasource1.ToList();
            result1.Insert(0, new { Code = -1, Name = "All" });
            this.comUnitType.DataSource = result1;
            this.comUnitType.DisplayMember = "Name";
            this.comUnitType.ValueMember = "Code";
            //
            this.comUnitType.SelectedIndexChanged += new System.EventHandler(this.comUnitType_SelectionChangeCommitted);
            SetUnits();
            // 单位性质
            var options2 = repository.All<ItemBase>();
            var datasource2 = from o in options2
                              where o.Type == "UnitKind" && o.IsValid == true
                              orderby o.Order
                              select new { Code = o.Code, Name = o.Name };
            var kinds = datasource2.ToList();
            kinds.Insert(0, new { Code = -1, Name = "All" });
            var result2 = kinds;
            this.comUnitKind.DataSource = result2;
            this.comUnitKind.DisplayMember = "Name";
            this.comUnitKind.ValueMember = "Code";
        }  
      
        #region GridGroupingControl Settings   
        private void InitializeGridGrouping()
        {
            foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(typeof(UnitModel)))
            {
                GridColumnDescriptor gcd = new GridColumnDescriptor(pd.Name, pd.Name, pd.Name, true, 100);
                if (pd.Name == "Name") gcd.Width = 300;
                this.gridList.TableDescriptor.Columns.Add(gcd);
            }
            // hide the trivial items
            this.gridList.TableDescriptor.GroupedColumns.Add("UnitType");
            this.gridList.TableDescriptor.VisibleColumns.Remove("Id");
            this.gridList.TableDescriptor.VisibleColumns.Remove("Subsidiary");
            this.gridList.TableDescriptor.VisibleColumns.Remove("IsValid");
            this.gridList.TableDescriptor.VisibleColumns.Remove("Contact");
            this.gridList.TableDescriptor.VisibleColumns.Remove("CreateDate");
            this.gridList.TableDescriptor.VisibleColumns.Remove("UnitTypeCode");
            this.gridList.TableDescriptor.AllowNew = false;
            this.gridList.TableDescriptor.Appearance.AnyRecordFieldCell.CellType = "Static";
            //
            //this.glOptions.Appearance.AlternateRecordFieldCell.Font.Facename = "Verdana";
            this.gridList.Appearance.AlternateRecordFieldCell.Interior = new BrushInfo(Color.Gainsboro);
            //
            this.gridList.TopLevelGroupOptions.ShowCaption = false;
            this.gridList.TopLevelGroupOptions.ShowAddNewRecordBeforeDetails = false;
            //
            this.gridList.TableOptions.GridVisualStyles = GridVisualStyles.Office2007Silver;
            this.gridList.TableOptions.GridLineBorder = new GridBorder(GridBorderStyle.Solid, Color.FromArgb(208, 215, 229), GridBorderWeight.Thin);
            //this.glOptions.TableOptions.ShowRowHeader = false;
            this.gridList.TableOptions.AllowSelection = GridSelectionFlags.None;
            this.gridList.TableOptions.ListBoxSelectionMode = SelectionMode.One;
            this.gridList.TableOptions.ListBoxSelectionCurrentCellOptions = GridListBoxSelectionCurrentCellOptions.HideCurrentCell;
            this.gridList.TableOptions.SelectionBackColor = Color.DarkOrange;
            this.gridList.TableOptions.SelectionTextColor = Color.Black;
            //
            this.gridList.ShowNavigationBar = true;
            //
            this.gridList.TableModel.Options.ShowCurrentCellBorderBehavior = GridShowCurrentCellBorder.HideAlways;
            //
            GridConditionalFormatDescriptor conditionalFormat = new GridConditionalFormatDescriptor();
            conditionalFormat.Appearance.AnyRecordFieldCell.Interior = new BrushInfo(Color.Wheat);
            conditionalFormat.Expression = "[IsValid] LIKE 'false'";
            this.gridList.TableDescriptor.ConditionalFormats.Add(conditionalFormat);

            this.gridList.DataSource = null;
        }
        #endregion

        private void btnSearch_Click(object sender, EventArgs e)
        {
            var unitType = (int)this.comUnitType.SelectedValue;
            var unitKind = (int)this.comUnitKind.SelectedValue;
            var unit = -1;
            if (this.comUnit.SelectedValue != null)
                unit = (int)this.comUnit.SelectedValue;

            SetupGroupingControl(unitType, unit, unitKind);
        }

        private void SetupGroupingControl(int unitType, int pId, int unitKind)
        {
            var predicate = PredicateBuilder.True<Unit>();
            
            if(unitType != -1)
                predicate = predicate.And(u => u.ParentUnit.UnitType.Code == unitType);
            if (unitKind != -1)
                predicate = predicate.And(u => u.UnitType.Code == unitKind);
            //
            if (pId != -1)
                predicate = predicate.And(u => u.ParentUnit.Id == pId);

            var datasource = repository.Find<Unit>(predicate.Expand());
            var result = from u in datasource
                             select new UnitModel
                             {
                                 Id = u.Id,
                                 Name = u.Name,
                                 Address = u.Address,
                                 Contact = u.Contact,
                                 Description = u.Description,
                                 IsValid = u.IsValid,
                                 CreateDate = u.CreateDate,
                                 UnitTypeCode = u.UnitType.Code,
                                 UnitType = u.UnitType.Name
                             };

            this.gridList.DataSource = result.ToList();
        }

        private void comUnitType_SelectionChangeCommitted(object sender, EventArgs e)
        {
            SetUnits();
        }
        private void SetUnits()
        {
            var unitType = this.comUnitType.SelectedValue;
            // 主管部门
            var units = repository.Find<Unit>(item => item.ParentUnit == null && item.UnitType.Code == (int)unitType);
            var datasource = from u in units
                             select new { Id = u.Id, Name = u.Name, Subsidiary = u.ChildUnits.Count, Addr = u.Address };

            var result = datasource.ToList();

            this.comUnit.DataSource = datasource.ToList();
            this.comUnit.DisplayMember = "Name";
            this.comUnit.ValueMember = "Id";
            //
            GridControl grid = this.comUnit.ListBox.Grid;
            grid.HideCols["Id"] = true;
          
            grid.QueryCellInfo += new GridQueryCellInfoEventHandler(gridList_QueryCellInfo);
            grid.PrepareViewStyleInfo += new GridPrepareViewStyleInfoEventHandler(gridList_PrepareViewStyleInfo);
           
        // System.Drawing.Graphics g = comboBox1.CreateGraphics(); 
         //float maxWidth = 0f; 
         //foreach(object o in comboBox1.Items) 
         //{ 
         //     float w = g.MeasureString(o.ToString(), comboBox1.Font).Width; 
         //     if(w > maxWidth) 
         //          maxWidth = w; 
         //} 
         //g.Dispose(); 
         //comboBox1.Width = (int) maxWidth + 20; // 20 is to take care of button width
        }

        #region MultiColumnComboBox GridListControl Events
        private void gridList_PrepareViewStyleInfo(object sender, GridPrepareViewStyleInfoEventArgs e)
        {
            if (e.ColIndex == 2 && e.RowIndex == 0)
            {
                e.Style.Text = "主管部门";
            }
            if (e.ColIndex == 3 && e.RowIndex == 0)
            {
                e.Style.Text = "下属单位";
            }
            if (e.ColIndex == 4 && e.RowIndex == 0)
            {
                e.Style.Text = "地址";
            }
        }

        private void gridList_QueryCellInfo(object sender, GridQueryCellInfoEventArgs e)
        {
            e.Style.TextColor = Color.Salmon;
        }
        #endregion

        private void comUnit_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.Handled == false)
            {
                if (this.comUnit.DroppedDown == false)
                {
                    this.comUnit.DroppedDown = true;
                }
            }
            else
            {
                this.comUnit.DroppedDown = false;
            }
        }
                

    }
}
